import eventBus from './event-bus'

var url = `${process.env.VUE_APP_WS_BASE_API}/websocket/`
var ws
// var tt
var lockReconnect = false
// 断线重连次数
var limitConnect = 3
var timeConnect = 0
// 30秒一次心跳
var timeout = 30 * 1000
var timeoutObj = null
var timeoutNum = null
// 心跳倒计时
var serverTimeoutObj = null

var websocket = {
  timeoutState: false,
  init: function(clientId) {
    const browserId = localStorage.getItem('browserId')
    if (!clientId.includes(browserId)) {
      clientId = clientId + ':' + browserId
    }
    console.log('webSocket.init', clientId)
    if ('WebSocket' in window) {
      ws = new WebSocket(url + clientId)
    } else if ('MozWebSocket' in window) {
      // eslint-disable-next-line no-undef
      ws = new MozWebSocket(url + clientId)
    } else {
      console.log('Your browser does not support WebSocket!')
      return
    }

    ws.onclose = function() {
      console.log('webSocket.onclose', clientId)
    }

    ws.onopen = function() {
      console.log('webSocket.onopen', clientId)
      websocket.start(clientId)
    }

    ws.onerror = function(e) {
      console.log('webSocket.onerror', e, clientId)
      ws.close()
      websocket.reconnect(clientId)
    }
  },
  send: function(content, receiver, status, timestamp) {
    console.log('websocket.send')
    const data = {
      content: content,
      receiver: receiver,
      status: status,
      timestamp: timestamp
    }
    const msg = JSON.stringify(data)
    ws.send(msg)
  },
  getWebSocket() {
    console.log('websocket.getWebSocket')
    return ws
  },
  getStatus() {
    console.log('websocket.getStatus')
    return ws.readyState
  },
  // 重新连接
  reconnect(clientId) {
    if (this.destroyedState) {
      console.log('websocket.reconnect.destroyedState')
      return
    }
    if (lockReconnect) {
      console.log('websocket.reconnect.lockReconnect')
      return
    }
    lockReconnect = true
    // 没连接上会一直重连，设置延迟避免请求过多
    timeoutNum && clearTimeout(timeoutNum)
    if (limitConnect > 0) {
      limitConnect--
      timeConnect++
      console.log('第' + timeConnect + '次重连')
      timeoutNum = setTimeout(() => {
        // 新连接
        console.log('websocket.reconnect', clientId)
        this.init(clientId)
        lockReconnect = false
      }, 5000)
    } else {
      console.log('websocket.reconnect')
      // 发布timeoutState超时连接事件，传递消息
      eventBus.emit('timeoutState', true)
    }
  },
  // 重置心跳
  reset(clientId) {
    console.log('websocket.reset')
    // 清除时间
    clearTimeout(timeoutObj)
    clearTimeout(serverTimeoutObj)
    // 重启心跳
    this.start(clientId)
  },
  // 开启心跳
  start(clientId) {
    timeoutObj && clearTimeout(timeoutObj)
    serverTimeoutObj && clearTimeout(serverTimeoutObj)
    timeoutObj = setTimeout(() => {
      console.log('websocket.start')
      if (websocket.getStatus() === 1) {
        ws.send('PING')
      } else {
        websocket.reconnect(clientId)
      }
    }, timeout)
  }
}

export default websocket
